from  tkinter import *
from tkinter.ttk import *
import tkinter as tk
import requests
from urllib import request
import urllib3
from PIL import Image,ImageTk
import io
import pandas as pd
import numpy as np
import webbrowser
import threading
from tkinter import messagebox
import crawler1

import view
# urllib3.disable_warnings()
# headers={
#         'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
#     }
# r = requests.get("https://webvpn.hitwh.edu.cn/http/77726476706e69737468656265737421a1a013d2756626062a46d8fa/loginCAS;jsessionid=20CA6EB2047F169826FFCA95E8E3B69E",headers=headers,verify=False)
# r.raise_for_status()
# r.encoding='utf-8'
# print(r.text)


class ui:
    img=[]
    image=[]
    url=[]
    def __init__(self,data):
        self.data=data
        self.root=Toplevel()
        self.root.title("推荐影片")
        self.width=1000
        self.height=700
        self.buttonWidth=(int)(self.width*0.1875)#150
        self.buttonHeight=(int)(self.height*0.3)#210
        self.buttonAirW=self.width*0.05
        self.buttonAirH=self.height*0.1
        self.root.geometry("{}x{}+100+0".format(self.width,self.height))
        self.button=[]
        self.name=[]
        if(len(data)<8):
            self.len=len(data)
        else:
            self.len=8
        for i in range(self.len):
            ui.img.append(Image.open(request.urlopen(data[i][11])))
            ui.img[len(ui.img)-1]=ui.img[len(ui.img)-1].resize((self.buttonWidth,self.buttonHeight))
            ui.img[len(ui.img)-1]=ImageTk.PhotoImage(ui.img[len(ui.img)-1])
            # 注意python是地址传递，i会导致恒为最后一个
            try:
                self.button.append(Button(self.root,image=ui.img[len(ui.img)-1],command=lambda index=i:self.detail(index)))
                self.name.append(Label(self.root,text=data[i][0],font=("宋体",20),justify=LEFT,wraplength=200))
                if(i<4):
                    self.button[i].place(x=self.buttonAirW*(i+1)+self.buttonWidth*i,y=self.buttonAirH)
                    self.name[i].place(x=self.buttonAirW*(i+1)+self.buttonWidth*i,y=self.buttonAirH+self.buttonHeight+self.buttonAirH*0.5)
                else:
                    j=i-4
                    self.button[i].place(x=self.buttonAirW*(j+1)+self.buttonWidth*j,y=self.buttonAirH*2.3+self.buttonHeight)
                    self.name[i].place(x=self.buttonAirW*(j+1)+self.buttonWidth*j,y=self.buttonAirH*2.3+self.buttonHeight*2+self.buttonAirH*0.5)
            except:
                pass
        # self.root.mainloop()
    def videoPlay(self,len):
        # 第三方播放解析地址
        port = 'https://jx.bozrc.com:4433/player/?url='
        ip=ui.url[len]
        print(ui.url[len])
        # path可自己更改，
        # path=r'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
        # webbrowser.register('chrome',None,webbrowser.BackgroundBrowser(path))
        # webbrowser.get('chrome').open(port+ip)
        webbrowser.open(port+ip)
    def detail(self,i):
        # print(i)
        self.detailWidth=(int)(self.width*0.8)
        self.root2=Toplevel()
        self.root2.title("详细信息")
        self.root2.geometry("{}x{}+200+50".format(self.detailWidth,self.height))
        ui.image.append(Image.open(request.urlopen(self.data[i][11])))
        ui.url.append(self.data[i][12])
        self.len=len(ui.image)-1
        self.imageWidth=ui.image[self.len].width*0.8
        self.imageWidth=int(self.imageWidth)
        self.imageHeight=ui.image[self.len].height*0.8
        self.imageHeight=int(self.imageHeight)
        ui.image[self.len]=ui.image[self.len].resize((self.imageWidth,self.imageHeight))
        ui.image[self.len]=ImageTk.PhotoImage(ui.image[self.len])
        self.data1=self.data[i]
        self.leftAir=self.detailWidth*0.1
        self.topAir=self.height*0.15
        self.secondtopAir=self.height*0.1
        self.secondleftAir=self.detailWidth*0.1
        self.elemAir=self.height*0.05
        self.labelTitle=Label(self.root2,text="{} ({})".format(self.data1[0],self.data1[1]),font=("宋体",40))
        self.labelTitle.place(x=self.leftAir,y=self.topAir)
        labelImage=Button(self.root2,image=ui.image[self.len],command=lambda x=self.len:self.videoPlay(x))
        labelImage.place(x=self.leftAir*1.2,y=self.topAir+self.secondtopAir)
        self.labelText=[]
        self.labelType=[]
        self.textWidth=35
        self.typeWidth=6
        buttonVideo=tk.Button(self.root2,text="点击播放",font=("宋体",20),width=10,command=lambda x=self.len:self.videoPlay(x))
        buttonVideo.place(x=self.leftAir*2+self.imageWidth+self.typeWidth*10+15*10,y=self.topAir+self.secondtopAir+15*4+self.elemAir*4)
        for j in range(7):
            self.labelType.append(Label(self.root2,font=("宋体",15),width=self.typeWidth))
            self.labelType[j].place(x=self.leftAir*2+self.imageWidth,y=self.topAir+self.secondtopAir+15*j+self.elemAir*j)
        for j in range(7):
            if j<4:
                self.labelText.append(Label(self.root2,text=self.data1[4+j],font=("宋体",15),width=self.textWidth))
            else:
                self.labelText.append(Label(self.root2,text=self.data1[4+j],font=("宋体",15)))
        self.labelType[0]['text']='导演：'
        self.labelType[1]['text']='编剧：'
        self.labelType[2]['text']='主演：'
        self.labelType[3]['text']='类型：'
        self.labelType[4]['text']='地区：'
        self.labelType[5]['text']='语言：'
        self.labelType[6]['text']='片长：'
        if(self.labelText[2]['text'].count('/')>=2):
            self.pos=self.labelText[2]['text'].find('/')
            self.pos=self.labelText[2]['text'].find('/',self.pos+1)
            self.labelText[2]['text']=self.labelText[2]['text'][:self.pos]+'等'
        if(self.labelText[1]['text'].count('/')>=2):
            self.pos=self.labelText[1]['text'].find('/')
            self.pos=self.labelText[1]['text'].find('/',self.pos+1)
            self.labelText[1]['text']=self.labelText[1]['text'][:self.pos]+'等'
        self.labelText[6]['text']=str(self.labelText[6]['text'])+'分钟'
        for j in range(7):
            self.labelText[j].place(x=self.leftAir*2+self.imageWidth+self.typeWidth*10,y=self.topAir+self.secondtopAir+15*j+self.elemAir*j)    
def choose1(e):
    widget=e.widget
    value=widget.get()
    res[0]=value
def choose2(e):
    widget=e.widget
    value=widget.get()
    res[1]=value
def Input1(e):
    widget=e.widget
    value=widget.get()
    res[2]=value
def Input2(e):
    widget=e.widget
    value=widget.get()
    res[3]=value
def search():
    data=pd.read_excel('top250.xlsx')
    data=data.values.tolist()
    res[2]=entry[0].get()
    res[3]=entry[1].get()
    searchData=[]
    for elem in data:
        if(res[0] not in elem[7] and res[0]!='不选择' and res[0]!='其他'):
            continue
        if(res[1]=='其他'):
            areaType=['中国','英国','美国','日本']
            judge=False
            for i in areaType:
                if(i in elem[8]):
                    judge=True
                    break
            if(judge):
                continue
        if(res[1] not in elem[8] and res[1]!='不选择' and res[1]!='其他'):
            continue
        if(res[0]=='其他'):
            movieType=['喜剧','爱情','动作','科幻','犯罪','惊悚','恐怖','冒险']
            judge=False
            for i in movieType:
                if(i in elem[7]):
                    judge=True
                    break
            if(judge):
                continue
        if(res[2] not in elem[4]):
            continue
        if(res[3] not in elem[6]):
            continue
        searchData.append(elem)
    ui(searchData)
def fresh():
    crawler1.run()
def logic():
    view.run()
if __name__=="__main__":
    root=Tk()
    root.title("影片筛选")
    width=600
    height=400
    fontHeight=int(height*0.05)
    airHeight=height*0.16
    airWidth=width*0.1
    buttonWidth=width*0.2
    root.geometry("{}x{}+400+150".format(width,height))
    combobox=[]
    label=[]
    for i in range(4):
        label.append(Label(root,font=("宋体",fontHeight)))
        label[i].place(x=airWidth,y=airHeight+i*(airHeight+fontHeight))
    label[0].config(text="类型")
    label[1].config(text="地区")
    label[2].config(text="导演")
    label[3].config(text="主演")
    for i in range(2):
        combobox.append(Combobox(root,state='readonly',height=10,width=6,font=("宋体",fontHeight)))
        combobox.append(Combobox(root,state='readonly',height=10,width=6,font=("宋体",fontHeight)))
    combobox[0].place(x=airWidth*2,y=airHeight)
    combobox[1].place(x=airWidth*2,y=airHeight*2+fontHeight)
    combobox[0].bind('<<ComboboxSelected>>',choose1)
    combobox[1].bind('<<ComboboxSelected>>',choose2)
    entry=[]
    for i in range(2):
        entry.append(Entry(root,width=10,font=("宋体",fontHeight)))
        entry[i].place(x=airWidth*2,y=airHeight+(i+2)*(airHeight+fontHeight))
    entry[0].bind('<FocusOut>',Input1)
    entry[1].bind('<FocusOut>',Input2)
    combobox[0]['value']=('不选择','喜剧','爱情','动作','科幻','犯罪','惊悚','恐怖','冒险','其他')
    combobox[1]['value']=('不选择','中国','英国','美国','日本','其他')
    combobox[0].current(0)
    combobox[1].current(0)
    buttonSearch=tk.Button(root,text="查询影片",width=10,font=('宋体',fontHeight,'bold'),command=lambda:threading.Thread(target=search).start())
    buttonLogic=tk.Button(root,text="分析影片",width=10,font=('宋体',fontHeight,'bold'),command=lambda:threading.Thread(target=logic).start())
    buttonCrawler=tk.Button(root,text="更新影片",width=10,font=('宋体',fontHeight,'bold'),command=lambda:threading.Thread(target=fresh).start())
    buttonSearch.place(x=airWidth*6,y=(height/5))
    buttonLogic.place(x=airWidth*6,y=height*0.45)
    buttonCrawler.place(x=airWidth*6,y=height*0.7)
    res=[]
    for i in range(4):
        res.append("")
    root.mainloop()

    